import React, { useCallback, useEffect, useState } from 'react';
import { Input, Button, Table, Space, Modal, message, Tag } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import {
  BuildGraphStatus,
  GraphItem,
  GraphListParams,
} from 'types/graph-builder';
import { graphBuilderApi } from 'services';
import dayjs from 'dayjs';

import GraphAdd from './GraphAdd';
import { renderStatusTag } from './helper';
import styles from './index.module.css';

const { Search } = Input;

const GraphBuilder: React.FC = () => {
  const navigate = useNavigate();
  const [modalVisible, setModalVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [graphRecords, setGraphRecords] = useState<GraphItem[]>([]);
  const [searchValue, setSearchValue] = useState('');
  // 添加分页参数
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 获取报告列表数据
  const fetchGraphs = useCallback(
    async (page: number, pageSize: number) => {
      setLoading(true);
      try {
        const params: GraphListParams = {
          page,
          pageSize,
        };
        if (searchValue) params.name = searchValue;

        const res = await graphBuilderApi.getGraphList(params);

        if (res.code === 200) {
          setGraphRecords(res.data.results);
          setPagination((prev) => ({
            ...prev,
            current: page,
            total: res.data.count,
          }));
        }
      } catch (error) {
        console.error('获取图谱构建列表失败:', error);
      } finally {
        setLoading(false);
      }
    },
    [searchValue]
  );

  // 监听筛选条件变化
  useEffect(() => {
    fetchGraphs(1, pagination.pageSize);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchValue]);

  const columns = [
    {
      title: '序号',
      key: 'index',
      width: 100,
      render: (_: any, __: any, index: number) => (
        <span className={styles.indexCell}>{index + 1}</span>
      ),
    },
    {
      title: '图谱名称',
      dataIndex: 'name',
      key: 'name',
      ellipsis: true,
      render: (text: string) => <span className={styles.nameCell}>{text}</span>,
    },
    {
      title: '构建方式',
      dataIndex: 'graph_type',
      key: 'graph_type',
      render: (type: string) => (
        <Tag
          color={type === 'structured' ? 'blue' : 'green'}
          className={styles.typeTag}
        >
          {type === 'structured' ? '结构化' : '非结构化'}
        </Tag>
      ),
    },
    {
      title: '构建状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: BuildGraphStatus) => renderStatusTag(status),
    },
    {
      title: '构建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (time: string) => (
        <span className={styles.timeCell}>
          {dayjs(time).format('YYYY-MM-DD HH:mm:ss')}
        </span>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_: unknown, record: GraphItem) => (
        <Space size="middle" className={styles.actionCell}>
          <Button
            type="link"
            className={styles.viewButton}
            onClick={() => handleView(record)}
          >
            查看
          </Button>
          <Button
            type="link"
            danger
            className={styles.deleteButton}
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 查看图谱
  const handleView = (record: GraphItem) => {
    navigate(`/graph-builder/view/${record.id}`);
  };

  // 删除图谱
  const handleDelete = (record: GraphItem) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除图谱"${record.name}"吗？`,
      onOk: () => {
        graphBuilderApi.deleteGraph(record.id).then((res) => {
          if (res.code === 200) {
            message.success('删除成功');
            fetchGraphs(1, pagination.pageSize);
          } else {
            message.error(res.message);
          }
        });
      },
    });
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          size="large"
          className={styles.createButton}
          onClick={() => setModalVisible(true)}
        >
          新建图谱
        </Button>
        <Search
          placeholder="请输入图谱名称搜索"
          onSearch={(value) => setSearchValue(value)}
          className={styles.searchInput}
          size="large"
          allowClear
        />
      </div>

      <Table<GraphItem>
        loading={loading}
        columns={columns}
        dataSource={graphRecords}
        rowKey="id"
        className={styles.table}
        pagination={{
          ...pagination,
          defaultPageSize: 5,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条记录`,
          className: styles.pagination,
          onChange: (page, pageSize) => {
            fetchGraphs(page, pageSize);
          },
        }}
      />

      {/* 添加图谱 Modal */}
      <GraphAdd modalVisible={modalVisible} setModalVisible={setModalVisible} />
    </div>
  );
};

export default GraphBuilder;
